package com.gientech.elasticsearchdemo.controller;

import com.gientech.elasticsearchdemo.entity.Book;
import com.gientech.elasticsearchdemo.service.BookService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;

@RestController
@RequestMapping
public class TestBookController {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    private BookService bookService;

    @GetMapping("/saveBook")
    public String saveBook(){

        Book book = new Book();
        book.setId("1");
        book.setBookName("Java程序设计");
        book.setPrice(30);

        bookService.save(book);

        return "添加成功";
    }

    @GetMapping("/search")
    public Object search(){
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(queryBuilder);
        NativeSearchQuery build = builder.build();

        SearchHits<Book> book = elasticsearchRestTemplate.search(build , Book.class);

        HashMap<Object, Object> objectHashMap = new HashMap<Object, Object>();
        objectHashMap.put("test_book", book.getSearchHits());
        objectHashMap.put("test_book_info", book.getSearchHits());

        return objectHashMap;
    }

    @GetMapping("/listAll")
    public Iterator<Book> all() {
        return bookService.findAll();
    }

    @GetMapping("/delete")
    public String delete(){
        //根据ID删除-indexName默认取@Document中indexName
        bookService.deleteById("1");
        return "删除成功";
    }


}
